const fs = require("fs");

const userService = require("../service/user.service");
const fileService = require("../service/file.service");
const { AVATAR_PATH } = require("../constants/file-path");

class UserController {
	async create(ctx, next) {
		// 获取用户请求传递的参数
		const user = ctx.request.body;
		// 创建用户
		const result = await userService.create(user);
		// 返回数据
		ctx.body = {
			code: 200,
			message: "创建用户成功",
			data: result
		};
	}

	async list(ctx, next) {
		const { offset, size } = ctx.query;
		const result = await userService.getUserList(offset, size);
		ctx.body = result;
	}

	async update(ctx, next) {
		const user = ctx.request.body;
		const user_id = ctx.user.id;
		const result = await userService.update(user, user_id);
		// 返回数据
		ctx.body = {
			code: 200,
			message: "修改信息成功",
			data: result
		};
	}

	async remove(ctx, next) {}

	async getAvatarInfo(ctx, next) {
		// 获取用户id
		const { userId } = ctx.params;
		// 查找用户头像
		const avatarInfo = await fileService.getAvatarInfo(userId);
		const { filename, mimetype } = avatarInfo;

		// 下载头像
		// ctx.body = fs.createReadStream(`${AVATAR_PATH}/${filename}`);

		// 返回头像（可读流）
		// ctx.response.set("content-type", mimetype);
		ctx.type = mimetype;
		ctx.body = fs.createReadStream(`${AVATAR_PATH}/${filename}`);
	}
}

module.exports = new UserController();
